<template>
  <div class="clothes-category-picker">
    <div class="picker-container">
      <van-field
        v-model="selectedCategoryText"
        :placeholder="placeholder"
        readonly
        is-link
        :label="label"
        input-align="right"
        @click="showPopup = true"
        class="category-picker"
      />
    </div>

    <!-- 使用vant的Picker组件实现分类选择 -->
    <van-popup v-model:show="showPopup" position="bottom" :round="true">
      <van-picker
        v-model="selectedIndexes"
        :columns="clothesCategories"
        :show-toolbar="true"
        :toolbar-actions="['取消', '确认']"
        @cancel="showPopup = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { clothesCategories } from "../utils/clothesCategory";

// Props
const props = defineProps({
  modelValue: {
    type: Object,
    default: null,
  },
  label: {
    type: String,
    default: "分类",
  },
  placeholder: {
    type: String,
    default: "选择分类",
  },
});

// Emits
const emit = defineEmits(["update:modelValue", "change"]);

// 响应式数据
const showPopup = ref(false);
const selectedIndexes = ref([]);
const selectedCategoryText = ref("");

/**
 * 根据modelValue更新显示的分类文本
 * 处理分类数组格式数据，支持一级和二级分类显示
 */
const updateDisplayFromModelValue = () => {
  try {
    if (!props.modelValue) {
      selectedCategoryText.value = "";
      return;
    }

    // 处理新的数组格式
    if (Array.isArray(props.modelValue) && props.modelValue.length > 0) {
      // 提取数组中的分类文本
      const categoryTexts = props.modelValue
        .filter(
          (category) =>
            category && typeof category === "object" && category.text
        )
        .map((category) => category.text);

      if (categoryTexts.length > 0) {
        selectedCategoryText.value = categoryTexts.join(" / ");
        return;
      }
    }

    // 兼容旧的对象格式
    if (typeof props.modelValue === "object" && props.modelValue.text) {
      if (
        props.modelValue.value &&
        typeof props.modelValue.value === "string" &&
        props.modelValue.value.includes("-")
      ) {
        // 二级分类
        const mainCategoryValue = props.modelValue.value.split("-")[0];
        const mainCategory = clothesCategories.find(
          (cat) => cat.value === mainCategoryValue
        );
        if (mainCategory) {
          selectedCategoryText.value = `${mainCategory.text} / ${props.modelValue.text}`;
        } else {
          // 如果找不到对应的一级分类，只显示当前分类文本
          selectedCategoryText.value = props.modelValue.text;
        }
      } else {
        // 一级分类
        selectedCategoryText.value = props.modelValue.text;
      }
    } else {
      selectedCategoryText.value = "";
    }
  } catch (error) {
    console.error("更新分类显示文本时出错:", error);
    selectedCategoryText.value = "";
  }
};

// 初始化时调用
updateDisplayFromModelValue();

// 监听modelValue变化，更新显示
watch(
  () => props.modelValue,
  () => {
    updateDisplayFromModelValue();
  },
  { deep: true }
); // 深度监听，确保对象内部属性变化也能被捕获

const onConfirm = ({ selectedValues, selectedOptions }) => {
  showPopup.value = false;

  // 确保selectedOptions存在且为数组
  if (
    !selectedOptions ||
    !Array.isArray(selectedOptions) ||
    selectedOptions.length === 0
  ) {
    return;
  }

  // 更新显示文本
  try {
    if (
      selectedOptions.length > 1 &&
      selectedOptions[1] &&
      selectedOptions[1].text
    ) {
      // 显示两级分类
      selectedCategoryText.value = `${selectedOptions[0].text} / ${selectedOptions[1].text}`;

      // 确保clothesCategories存在且为数组
      if (
        clothesCategories &&
        Array.isArray(clothesCategories) &&
        clothesCategories.length > 0
      ) {
        // 发射事件，传递包含两级分类数据的对象数组
        const mainCategory = clothesCategories.find(
          (cat) => cat.text === selectedOptions[0].text
        );
        if (
          mainCategory &&
          mainCategory.children &&
          Array.isArray(mainCategory.children)
        ) {
          const selectedCategory = mainCategory.children.find(
            (child) => child.text === selectedOptions[1].text
          );

          if (selectedCategory && typeof selectedCategory === "object") {
            // 创建包含两级分类数据的数组
            const categoryData = [
              { ...mainCategory, children: undefined }, // 一级分类（移除children属性）
              { ...selectedCategory }, // 二级分类
            ];
            emit("update:modelValue", categoryData);
            emit("change", categoryData);
          }
        }
      }
    } else {
      // 只显示一级分类
      selectedCategoryText.value = selectedOptions[0].text;

      // 确保clothesCategories存在且为数组
      if (
        clothesCategories &&
        Array.isArray(clothesCategories) &&
        clothesCategories.length > 0
      ) {
        // 发射事件，传递包含一级分类数据的对象数组
        const selectedCategory = clothesCategories.find(
          (cat) => cat.text === selectedOptions[0].text
        );

        if (selectedCategory && typeof selectedCategory === "object") {
          // 创建包含一级分类数据的数组
          const categoryData = [
            { ...selectedCategory, children: undefined }, // 一级分类（移除children属性）
          ];
          emit("update:modelValue", categoryData);
          emit("change", categoryData);
        }
      }
    }
  } catch (error) {
    console.error("处理分类选择时出错:", error);
  }
};
</script>

<style scoped>
.clothes-category-picker {
  margin-bottom: 20px;
}

.picker-container {
  width: 100%;
}

.category-picker {
  width: 100%;
}
</style>
